package com.kedacom.demo.modb.movision.service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kedacom.demo.modb.movision.dao.AccountDao;
import com.kedacom.demo.modb.movision.model.Account;
import com.kedacom.demo.modb.rabbitmq.gateway.ModbMessageGateway;
import com.kedacom.demo.modb.rabbitmq.message.CreateAccountEventMessage;
import com.kedacom.demo.modb.rabbitmq.message.CreateAccountSqlAndEventMessage;

/**
 * 用户帐号管理业务实现
 * @author luocanfeng
 * @date 2013-1-10
 */
@Transactional
@Service("accountService")
public class AccountServiceImpl implements AccountService {

	@Value("#{rabbitmq['rabbitmq.routingkey.event.topublic']}")
	private String routingKeyToPublicEvent;

	@Value("#{rabbitmq['rabbitmq.routingkey.sqlevent.toprivate']}")
	private String routingKeyToPrivateSqlEvent;

	@Resource
	private AccountDao accountDao;

	@Resource(name = "apJdbcDaoSupport")
	private JdbcDaoSupport apJdbcDaoSupport;

	@Resource
	private ModbMessageGateway modbMessageGateway;

	private String createAccountSql = "insert into account(company_moid,is_public,moid,email,e164,password,jid,name,sex,seat,ext_num,mobile_num,position,brief,created_at)"
			+ " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

	@Override
	public List<Account> listAll() {
		return accountDao.listAll();
	}

	@Override
	public void createAccount(Account account) {
		preProcessAccountForCreating(account);

		// TODO MoDB方案缺陷一：业务方法需要清楚持久化（sql）细节
		Object[] sqlArgs = new Object[] {
				account.getCompanyMoid(), account.isPublicCompanyAccount(), account.getMoid(), account.getEmail(),
				account.getE164(), account.getPassword(), account.getJid(), account.getRealName(), account.getSex(),
				account.getSeat(), account.getExtNum(), account.getMobile(), account.getPosition(), account.getBrief(),
				account.getCreatedAt()
		};
		// persist to db
		apJdbcDaoSupport.getJdbcTemplate().update(createAccountSql, sqlArgs);

		if (account.isPublicCompanyAccount()) {
			modbMessageGateway.sendModbMessage(routingKeyToPublicEvent,
					new CreateAccountEventMessage(account.getMoid()));
		} else {
			// FIXME hard code
			String companyMoid = account.getCompanyMoid();
			String companyIdentify = "";
			if (companyMoid.contains("kedacom")) {
				companyIdentify = "kedacom";
			} else if (companyMoid.contains("huawei")) {
				companyIdentify = "huawei";
			}
			modbMessageGateway.sendModbMessage(routingKeyToPrivateSqlEvent + "." + companyIdentify,
					new CreateAccountSqlAndEventMessage(account.getMoid(), createAccountSql, sqlArgs));
		}
	}

	private Account preProcessAccountForCreating(Account account) {
		account.setMoid(UUID.randomUUID().toString());
		account.setPassword(new String(DigestUtils.md5Hex(account.getPassword())));
		account.setJid(account.getMoid());
		account.setCreatedAt(new Date());
		return account;
	}

}
